package com.example.demo.common.utils;

import com.example.demo.common.dto.MergeCellsDTO;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ExcelExportUtils {
    public static ByteArrayOutputStream mergeCells(InputStream inputStream, List<MergeCellsDTO> mergeCols) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            // 加载Excel文件
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (MergeCellsDTO r : mergeCols) {
                int firstRow = r.getFirstRow();
                int lastRow = r.getLastRow();
                int firstCol = r.getFirstCol();
                int lastCol = r.getLastCol();

                // 合并单元格只有一个单元格时，不合并 by lufer.chen
                if (lastRow == firstRow && lastCol == firstCol) {
                    continue;
                }

                // 合并单元格
                CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
                sheet.addMergedRegion(region);

                // 设置合并后的单元格边框样式
                RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet);
                RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet);
                RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet);
                RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet);
            }

            workbook.write(byteArrayOutputStream);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream;
    }
}
